package com.youpai.yingteda_android.util



import com.streamer.app.utils.SPUtils
import com.streamer.app.utils.http.Contacts.Companion.KEY_USER_TOKEN
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


/**
 * author:cb
 * createTime: 2021/3/22 15:31
 **/
object Net {
    lateinit var retrofit: Retrofit
    fun initConfig(baseUrl: String) {
        retrofit = Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(createClient())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }


    fun <T> create(c: Class<T>): T {
        return retrofit.create(c)
    }

    private fun createClient(): OkHttpClient {
        val clientBuilder = OkHttpClient.Builder()
        clientBuilder.readTimeout(60000L,TimeUnit.MILLISECONDS)
        clientBuilder.connectTimeout(60000L,TimeUnit.MILLISECONDS)
        clientBuilder.writeTimeout(60000L,TimeUnit.MILLISECONDS)
        clientBuilder.addInterceptor {
            val requestBuilder = it.request().newBuilder()
            val userToken= SPUtils.getInstance().getString(KEY_USER_TOKEN)
            if(userToken.isNotEmpty()){
//                requestBuilder.addHeader("token", userToken)
                requestBuilder.addHeader("Authorization", "Bearer "+userToken)
            }
            requestBuilder.addHeader("clientid", "a2e43345f6a0f2f64f2fb15fdfca21cf")

            it.proceed(requestBuilder.build())
        }
        // 添加日志拦截器用于调试
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        clientBuilder.addInterceptor(loggingInterceptor)
        return clientBuilder.build()
    }


}